const API_LATEST = "/api/latest";
const API_HISTORY = (id, limit=20) => `/api/history/${id}?limit=${limit}`;

let timer = null;
const tableBody = document.getElementById("tableBody");
const totalIds = document.getElementById("totalIds");
const lastUpdated = document.getElementById("lastUpdated");
const emptyHint = document.getElementById("emptyHint");
const filterInput = document.getElementById("filterInput");
const intervalSelect = document.getElementById("intervalSelect");
const refreshBtn = document.getElementById("refreshBtn");

const activeCount = document.getElementById("activeCount");
const latestId = document.getElementById("latestId");
const latestTime = document.getElementById("latestTime");

const themeSelect = document.getElementById("themeSelect");
const clearBtn = document.getElementById("clearBtn");

// 工具函数
function fmtTime(tsSec) {
  if (!tsSec) return "—";
  const d = new Date(tsSec * 1000);
  return d.toLocaleString();
}
function nowSec() { return Math.floor(Date.now() / 1000); }
function esc(s) { return (s ?? "").toString().replace(/[&<>"']/g, m => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[m])); }
function ageSec(ts) { return Math.max(0, nowSec() - ts); }
function statusDot(age) {
  // 0-10s 绿，10-60s 黄，>60s 灰
  let cls = "dot-gray";
  if (age <= 10) cls = "dot-green";
  else if (age <= 60) cls = "dot-yellow";
  return `<span class="dot ${cls}" title="延时 ${age}s"></span>`;
}

async function fetchLatest() {
  const resp = await fetch(API_LATEST, { cache: "no-store" });
  if (!resp.ok) throw new Error("获取最新数据失败");
  return await resp.json();
}

function render(rows) {
  const q = filterInput.value.trim().toLowerCase();
  // 计算活跃ID数：ts 在 60s 内的 ID
  const ACTIVE_WINDOW = 60; // 秒
  const active = rows.filter(r => (nowSec() - r.ts) <= ACTIVE_WINDOW).length;

  // 最近上传（按 ts；若相同再看 received_at）
  const latest = rows.reduce((best, cur) => {
    if (!best) return cur;
    if (cur.ts !== best.ts) return cur.ts > best.ts ? cur : best;
    // ts 相同则比较服务器接收时间（/api/latest 里有 returned received_at）
    if ((cur.received_at ?? 0) !== (best.received_at ?? 0)) {
      return (cur.received_at ?? 0) > (best.received_at ?? 0) ? cur : best;
    }
    return best;
  }, null);

  activeCount.textContent = active;
  latestId.textContent = latest ? latest.id : "—";
  latestTime.textContent = latest ? fmtTime(latest.ts) : "—";
  lastUpdated.textContent = new Date().toLocaleTimeString();

  const filtered = rows.filter(r => {
    if (!q) return true;
    return String(r.id).includes(q) || (r.username || "").toLowerCase().includes(q);
  });

  if (filtered.length === 0) {
    tableBody.innerHTML = "";
    emptyHint.style.display = "block";
    return;
  }
  emptyHint.style.display = "none";

  // 新增：按 ts 降序（最新在上）
  const sorted = filtered.slice().sort((a, b) => b.ts - a.ts);

  const html = sorted.map(r => {
    const a = ageSec(r.ts);
    return `<tr>
      <td class="mono">${esc(r.id)}</td>
      <td>${esc(r.username || "—")}</td>
      <td class="mono">${Number(r.value).toFixed(4)}</td>
      <td class="mono">${fmtTime(r.ts)}</td>
      <td class="mono">${a}</td>
      <td>${statusDot(a)}</td>
      <td><button class="link" data-id="${r.id}">查看</button></td>
    </tr>`;
  }).join("");
  tableBody.innerHTML = html;

  // 绑定“查看历史”
  tableBody.querySelectorAll("button.link").forEach(btn => {
    btn.onclick = async () => {
      const id = btn.getAttribute("data-id");
      const resp = await fetch(API_HISTORY(id, 50));
      if (!resp.ok) return alert("获取历史失败");
      const items = await resp.json();
      const text = items.map(x => `${fmtTime(x.ts)}  value=${x.value}  user=${x.username ?? "—"}`).join("\n");
      alert(`ID ${id} 最近 ${items.length} 条：\n\n${text}`);
    };
  });
}

//主题切换
function applyTheme(mode) {
  const root = document.documentElement;
  if (mode === "light") {
    root.setAttribute("data-theme", "light");
  } else if (mode === "dark") {
    root.setAttribute("data-theme", "dark");
  } else {
    // auto: 移除强制主题，走系统偏好
    root.removeAttribute("data-theme");
  }
  localStorage.setItem("theme-mode", mode);
}

//清除数据库
if (clearBtn) clearBtn.onclick = async () => {
  if (!confirm("确定要清空数据库并从零开始吗？此操作不可撤销。")) return;
  clearBtn.disabled = true;
  try {
    const resp = await fetch("/api/clear", { method: "POST" });
    if (!resp.ok) {
      const txt = await resp.text();
      throw new Error(`清空失败：${txt}`);
    }
    // 清空页面显示
    render([]);                       // 表格置空
    lastUpdated.textContent = new Date().toLocaleTimeString();
    // 也可以适当清空统计
    if (typeof activeCount !== "undefined") activeCount.textContent = 0;
    if (typeof latestId !== "undefined") latestId.textContent = "—";
    if (typeof latestTime !== "undefined") latestTime.textContent = "—";
  } catch (e) {
    alert(e.message || e);
  } finally {
    clearBtn.disabled = false;
  }
};


// 初始化：读本地、默认 auto
const savedTheme = localStorage.getItem("theme-mode") || "auto";
themeSelect.value = savedTheme;
applyTheme(savedTheme);

// 切换事件
themeSelect.onchange = () => applyTheme(themeSelect.value);

async function tick() {
  try {
    const rows = await fetchLatest();
    render(rows);
  } catch (e) {
    console.error(e);
  }
}

function startPolling() {
  if (timer) clearInterval(timer);
  const sec = Number(intervalSelect.value);
  timer = setInterval(tick, sec * 1000);
}

intervalSelect.onchange = startPolling;
refreshBtn.onclick = tick;
filterInput.oninput = tick;

tick();           // 立即加载一次
startPolling();   // 开始轮询
